<template>
  <!-- 用户列表 -->
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.name" clearable
            @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户
          </el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="phone"></el-table-column>
        <el-table-column label="角色" prop="username"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.status" active-color="#409eff"
              inactive-color="#dcdfe6" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini"
              @click="showEditDialog(scope.row.id)">
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="removeUserById(scope.row.id)">
            </el-button>
            <!-- 分配角色 -->
            <el-tooltip class="item" effect="dark" content="分配角色"
              placement="top" :enterable=false>
              <el-button type="warning" icon="el-icon-setting" size="mini"
                @click="setRole(scope.row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="queryInfo.page" :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" modal
      :close-on-click-modal=false @close="addDialogClosed">
      <!-- 对话框内容 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"
        label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="密码确认" prop="password2">
          <el-input v-model="addForm.password2" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone" clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <!-- 确认，取消按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" modal
      :close-on-click-modal=false @close="editDialogClosed">
      <!-- 对话框内容 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef"
        label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="editForm.phone" clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <!-- 确认，取消按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="提示" :visible.sync="setRoleDialogVisible" width="50%" modal
      :close-on-click-modal=false>
      <div class="set-role">
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <span>分配的新角色：</span>
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option v-for="item in roleList" :key="item.id"
            :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script  >

import { userList,userLock } from '../../api/userMG'
import store from '../../main.js';

export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9])+/
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法手机号
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }

      //密码确认  判断与password是否相同
    const checkPassword = (rule, value, callback) => {

      if(value !== this.addForm.password){
         return callback(new Error('2次密码填写不一致'))
      }
      //如果相同,则调用回调函数
      callback()
    }
    return {
      // 获取用户列表的请求参数对象
      queryInfo: {
        name: '',
        // 当前的页数
        page: 1,
        // 每页的条数
        pageSize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示和隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示和隐藏
      editDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        password2:'',
        email: '',
        phone: ''
      },
      // 添加用户的表单数据的验证对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
           password2: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
            { validator: checkPassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑的用户信息对象
      editForm: {},
      // 编辑用户的表单数据的验证对象
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的列表
      roleList: [],
      // 已选中角色的id值
      selectedRoleId: null
    }
  },
  methods: {
    // 获取用户数据
     getUserList() {
      userList(this.queryInfo).then(res => {
        this.loading = false
        if (res.status == 200) { {
          this.userList = res.data.list
          this.total = res.data.totalCount
        }
      }})
    },
    // 监听分页器 pageSize 改变, 重新发送获取用户数据的请求
    handlePageSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    // 监听分页器 页码 改变的事件, 重新发送获取用户数据的请求
    handleCurrentPageChange(newPage) {
      this.queryInfo.page = newPage
      this.getUserList()
    },
    // 监听Switch开关的改变，即用户状态的改变，然后发送请求，保存用户的状态
    async userStateChanged(userInfo) {
        userLock(userInfo).then(res => {
        this.loading = false
        if (res.status == 200) {
            this.$message.success('更新用户状态成功')
        }else
        {
            userInfo.status = !userInfo.status
            this.$message.error('更新用户状态失败')
        }
      })
    },
    // 监听用户关闭添加用户对话框的关闭,清空表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户对话框确定按钮，添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 发送添加用户的网络请求
        const { data: res } = await this.$http.post('user/insert', this.addForm)
        if (res.status !== 200) {
          return this.$message.error('添加用户失败，请重新添加')
        }
        this.$message.success('添加用户成功')
        // 关闭对话框
        this.addDialogVisible = false
        // 清空表单
        this.$refs.addFormRef.resetFields()
        // 重新获取用户列表
        this.getUserList()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      // 显示对话框
      this.editDialogVisible = true
      // 发送根据用户id查询用户信息请求
      const { data: res } = await this.$http.get('user/' + id)
      if (res.status !== 200) {
        return this.$message.error('查询用户失败')
      }
      console.log(res.data)
      this.editForm = res.data


    },
    // 编辑用户的对话框关闭
    editDialogClosed() {
      // 清空表单的验证结果
      this.$refs.editFormRef.resetFields()
    },
    // 编辑用户对话框确定按钮，修改用户信息
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息请求
        const { data: res } = await this.$http.put(
          'user/update',
          {
            id: this.editForm.id,
            email: this.editForm.email,
            phone: this.editForm.phone
          }
        )
        if (res.status !== 200)
          return this.$message.error('更新用户信息失败')
        // 刷新用户列表
        this.getUserList()
        // 关闭对话框
        this.editDialogVisible = false
        // 提示修改成功
        this.$message.success('更新用户信息成功')
      })
    },
    // 根据id删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问是否删除
      await this.$msgBox
        .confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        })
        .then(async () => {
          // 确定，发送删除用户请求
          const { data: res } = await this.$http.delete('user/' + id)
          if (res.status !== 200)
            return this.$message.error('删除用户失败')
          // 重新获取用户列表
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 展示分配角色对话框
    async setRole(userInfo) {
      this.selectedRoleId = null
      this.userInfo = userInfo
      // 在展示对话框之前，获取所有角色的列表
      const { data: res } = await this.$http.get('role/list')
      if (res.status !== 200)
        return this.$message.error('获取角色列表失败')
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    // 分配角色对话框点击确定，分配角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) return this.$message.info('请选择要分配的角色')
      const { data: res } = await this.$axios1.put(
        `user/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      if (res.meta.status !== 200) return this.$message('更新角色失败')
      this.$message.success('更新角色成功')
      // 刷新用户列表
      this.getUserList()
      // 关闭对话框
      this.setRoleDialogVisible = false
    }
  },
  created() {
    this.getUserList()
  }
}
</script>

<style scoped>
.set-role p {
  margin-bottom: 20px;
}
</style>
